/**
 * Copyright (c) 2011 eelpo.com
 * All rights reserved.
 */
package com.eelpo.cmmp.uac.pages.user;

import java.util.Arrays;
import java.util.List;

import com.eelpo.cmmp.basic.dao.vo.SystemConfig;
import com.eelpo.cmmp.basic.services.ISystemConfigManageService;
import com.eelpo.cmmp.core.exception.ServiceException;
import com.eelpo.cmmp.core.wicket.behavior.ComponentVisualErrorBehavior;
import com.eelpo.cmmp.core.wicket.component.label.FeedbackLabel;
import com.eelpo.cmmp.core.wicket.page.extensions.SimpleWebPage;
import com.eelpo.cmmp.uac.constants.SystemConfigConstants;
import com.eelpo.cmmp.uac.dao.vo.User;
import com.eelpo.cmmp.uac.dao.vo.enumed.AuthMode;
import com.eelpo.cmmp.uac.dao.vo.enumed.Status;
import com.eelpo.cmmp.uac.dao.vo.enumed.YesOrNo;
import com.eelpo.cmmp.uac.services.IUserManageService;
import com.eelpo.common.util.BlankUtils;
import com.eelpo.common.util.StringUtils;

import org.apache.wicket.markup.html.form.Button;
import org.apache.wicket.markup.html.form.ChoiceRenderer;
import org.apache.wicket.markup.html.form.DropDownChoice;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.IChoiceRenderer;
import org.apache.wicket.markup.html.form.PasswordTextField;
import org.apache.wicket.markup.html.form.TextArea;
import org.apache.wicket.markup.html.form.TextField;
import org.apache.wicket.markup.html.link.Link;
import org.apache.wicket.model.IModel;
import org.apache.wicket.model.Model;
import org.apache.wicket.model.PropertyModel;
import org.apache.wicket.spring.injection.annot.SpringBean;
import org.apache.wicket.validation.validator.PatternValidator;
import org.apache.wicket.validation.validator.StringValidator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * <pre>
 * 
 * 新增和修改用户页面
 * 
 * </pre>
 * 
 * @author <a href="mailto:Brian@eelpo.com">汪洪州</a>
 * @since 1.0
 */
public class AddOrEditUser extends SimpleWebPage {

	private static final Logger logger = LoggerFactory.getLogger(AddOrEditUser.class);

	@SpringBean
	protected IUserManageService userManageService;

	@SpringBean
	protected ISystemConfigManageService systemConfigManageService;

	/**
	 * 
	 * 新增用户构造函数
	 * 
	 */
	public AddOrEditUser() {
		this("[新增]用户", new User(Status.ENABLED, YesOrNo.YES, YesOrNo.NO, AuthMode.PASSWORD, AuthMode.PASSWORD));
	}

	/**
	 * 修改用户构造函数
	 * 
	 * @param user
	 *            用户
	 */
	public AddOrEditUser(final User user) {
		this("[修改]用户", user);
	}

	/**
	 * @param title
	 *            页面标题
	 * @param user
	 *            新增或修改的用户
	 */
	public AddOrEditUser(String title, final User user) {
		super(title);

		add(renderFormContainer(user));
	}

	public Form<User> renderFormContainer(final User user) {

		Form<User> form = new Form<User>("form", new Model<User>(user));

		renderFeedbackPanel(form);
		renderUserNameTextField(form);
		renderUserMobileTextField(form);
		renderUserAccountTextField(form);
		renderUserPasswordTextField(form);
		renderUserDescriptionTextArea(form);
		renderUserStatusDropDownChoice(form);
		renderUserWebLoginDropDownChoice(form);
		renderUserWebAuthDropDownChoice(form);
		renderUserInterfaceLoginDropDownChoice(form);
		renderUserInterfaceAuthDropDownChoice(form);
		renderSaveButton(form);
		renderBackButton(form);
		return form;
	}

	public void renderFeedbackPanel(Form<User> form) {
		form.add(renderFeedbackPanel("feedback"));
	}

	public void renderUserNameTextField(Form<User> form) {
		TextField<String> txtName = new TextField<String>("txtName", new PropertyModel<String>(form.getDefaultModelObject(), "name"));
		txtName.setMarkupId("txtName");
		form.add(new FeedbackLabel("txtNameFeedback", txtName));
		form.add(txtName);
	}

	public void renderUserMobileTextField(Form<User> form) {
		TextField<String> txtMoblie = new TextField<String>("txtMoblie", new PropertyModel<String>(form.getDefaultModelObject(), "mobile"));
		txtMoblie.setMarkupId("txtMoblie");
		form.add(new FeedbackLabel("txtMoblieFeedback", txtMoblie));
		form.add(txtMoblie);
	}

	public void renderUserAccountTextField(Form<User> form) {
		TextField<String> txtAccount = new TextField<String>("txtAccount", new PropertyModel<String>(form.getDefaultModelObject(), "account"));
		txtAccount.setMarkupId("txtAccount");
		form.add(new FeedbackLabel("txtAccountFeedback", txtAccount));
		form.add(txtAccount);
	}

	public void renderUserPasswordTextField(Form<User> form) {
		PasswordTextField txtPassword = new PasswordTextField("txtPassword", new PropertyModel<String>(form.getDefaultModelObject(), "password"));
		txtPassword.setMarkupId("txtPassword");
		txtPassword.setResetPassword(false);

		// 获取密码最少长度
		int minimum = 10;

		try {
			SystemConfig config = systemConfigManageService.getSystemConfigByKey(SystemConfigConstants.PASSWORD_LENGTH);
			if (StringUtils.isInteger(config.getConfigValue())) {
				minimum = Integer.parseInt(config.getConfigValue());
			}
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		txtPassword.add(StringValidator.minimumLength(minimum));

		// 获取密码正则表达式
		String regular = "^\\w+$";

		try {
			SystemConfig config = systemConfigManageService.getSystemConfigByKey(SystemConfigConstants.PASSWORD_REGULAR);
			regular = config.getConfigValue();
			txtPassword.setLabel(new Model<String>(config.getHint()));
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		txtPassword.add(new PatternValidator(regular));

		FeedbackLabel txtPasswordFeedback = new FeedbackLabel("txtPasswordFeedback", txtPassword);
		txtPassword.add(new ComponentVisualErrorBehavior("onkeyup", txtPasswordFeedback));
		form.add(txtPassword);
		form.add(txtPasswordFeedback);
	}

	public void renderUserDescriptionTextArea(Form<User> form) {
		form.add(new TextArea<String>("txtDescription", new PropertyModel<String>(form.getDefaultModelObject(), "description")));
	}

	public void renderUserStatusDropDownChoice(final Form<User> form) {
		List<Status> dataList = Arrays.asList(new Status[] { Status.ENABLED, Status.DISABLED });
		IModel<Status> model = new PropertyModel<Status>(form.getDefaultModelObject(), "status");
		IChoiceRenderer<Status> choiceRenderer = new ChoiceRenderer<Status>("label", "value");
		DropDownChoice<Status> userStatus = new DropDownChoice<Status>("selStatus", model, dataList, choiceRenderer);
		userStatus.setMarkupId("selStatus");
		form.add(new FeedbackLabel("selStatusFeedback", userStatus));
		form.add(userStatus);
	}

	public void renderUserWebLoginDropDownChoice(final Form<User> form) {
		List<YesOrNo> dataList = Arrays.asList(new YesOrNo[] { YesOrNo.YES, YesOrNo.NO });
		IModel<YesOrNo> model = new PropertyModel<YesOrNo>(form.getDefaultModelObject(), "allowWebLogin");
		IChoiceRenderer<YesOrNo> choiceRenderer = new ChoiceRenderer<YesOrNo>("label", "value");
		DropDownChoice<YesOrNo> userWebLogin = new DropDownChoice<YesOrNo>("selWeblogin", model, dataList, choiceRenderer);
		userWebLogin.setMarkupId("selWeblogin");
		form.add(new FeedbackLabel("selWebloginFeedback", userWebLogin));
		form.add(userWebLogin);
	}

	public void renderUserWebAuthDropDownChoice(final Form<User> form) {
		List<AuthMode> dataList = Arrays.asList(new AuthMode[] { AuthMode.PASSWORD, AuthMode.IP, AuthMode.PASSWORDIP });
		IModel<AuthMode> model = new PropertyModel<AuthMode>(form.getDefaultModelObject(), "webAuthMode");
		IChoiceRenderer<AuthMode> choiceRenderer = new ChoiceRenderer<AuthMode>("label", "value");
		DropDownChoice<AuthMode> userWebAuth = new DropDownChoice<AuthMode>("selWebauth", model, dataList, choiceRenderer);
		userWebAuth.setMarkupId("selWebauth");
		form.add(new FeedbackLabel("selWebauthFeedback", userWebAuth));
		form.add(userWebAuth);
	}

	public void renderUserInterfaceLoginDropDownChoice(final Form<User> form) {
		List<YesOrNo> dataList = Arrays.asList(new YesOrNo[] { YesOrNo.YES, YesOrNo.NO });
		IModel<YesOrNo> model = new PropertyModel<YesOrNo>(form.getDefaultModelObject(), "allowInterface");
		IChoiceRenderer<YesOrNo> choiceRenderer = new ChoiceRenderer<YesOrNo>("label", "value");
		DropDownChoice<YesOrNo> userItfLogin = new DropDownChoice<YesOrNo>("selInterfacelogin", model, dataList, choiceRenderer);
		userItfLogin.setMarkupId("selInterfacelogin");
		form.add(new FeedbackLabel("selItfloginFeedback", userItfLogin));
		form.add(userItfLogin);
	}

	public void renderUserInterfaceAuthDropDownChoice(final Form<User> form) {
		List<AuthMode> dataList = Arrays.asList(new AuthMode[] { AuthMode.PASSWORD, AuthMode.IP, AuthMode.PASSWORDIP });
		IModel<AuthMode> model = new PropertyModel<AuthMode>(form.getDefaultModelObject(), "interfaceAuthMode");
		IChoiceRenderer<AuthMode> choiceRenderer = new ChoiceRenderer<AuthMode>("label", "value");
		DropDownChoice<AuthMode> userItfAuth = new DropDownChoice<AuthMode>("selInterfaceauth", model, dataList, choiceRenderer);
		userItfAuth.setMarkupId("selInterfaceauth");
		form.add(new FeedbackLabel("selItfauthFeedback", userItfAuth));
		form.add(userItfAuth);
	}

	public void renderSaveButton(final Form<User> form) {
		Button btnSave = new Button("btnSave") {
			private static final long serialVersionUID = 6855404939131434877L;

			public void onSubmit() {
				try {

					User user = (User) form.getDefaultModelObject();

					if (BlankUtils.isBlank(user.getId())) {
						userManageService.addUser(user);
					} else {
						userManageService.updateUser(user);
					}

					setResponsePage(new UserManage());
				} catch (ServiceException ex) {
					info(ex.getMessage());
				} catch (Exception e) {
					e.printStackTrace();
					info("保存失败！");
				}
			}
		};

		form.add(btnSave);
	}

	public void renderBackButton(final Form<User> form) {
		Link<Void> btnBack = new Link<Void>("btnBack") {

			private static final long serialVersionUID = -9129976099407032628L;

			@Override
			public void onClick() {
				setResponsePage(new UserManage());
			}
		};

		form.add(btnBack);
	}
}
